/**
 * 加载状态Hook
 */
import { ref, readonly } from 'vue';

export function useLoading(initialState = false) {
  const loading = ref(initialState);

  const setLoading = (state: boolean) => {
    loading.value = state;
  };

  const startLoading = () => {
    loading.value = true;
  };

  const stopLoading = () => {
    loading.value = false;
  };

  const withLoading = async <T>(fn: () => Promise<T>): Promise<T> => {
    try {
      startLoading();
      return await fn();
    } finally {
      stopLoading();
    }
  };

  return {
    loading: readonly(loading),
    setLoading,
    startLoading,
    stopLoading,
    withLoading,
  };
}
